package com.zcp.todayheadline.adapter;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.zcp.todayheadline.Main2Activity;
import com.zcp.todayheadline.R;
import com.zcp.todayheadline.bean.NewsSummary;

import java.util.List;

/**
 * Created by Administrator on 2017/1/9.
 */

public class MyBase extends BaseAdapter {
    Context context;
    List<NewsSummary> list;
    final static int TYPE_ITEM1 = 0;
    final static int TYPE_ITEM2 = 1;
    final static int TYPE_ITEM3 = 2;

    public static PopupWindow mCurPopupWindow;
    LayoutInflater inflater;

    public MyBase() {
    }

    public MyBase(Context context, List<NewsSummary> list) {
        this.context = context;
        this.list = list;
        this.inflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public NewsSummary getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        int type = getItemViewType(position);
        ViewHolder vh1 = null;
        ViewHolder vh2 = null;
        ViewHolder vh3 = null;

        //找控件
        if (convertView == null) {
            switch (type) {
                case 0:
                    convertView = inflater.inflate(R.layout.lv_item3, parent, false);
                    vh3 = new ViewHolder(convertView);
                    convertView.setTag(vh3);
                    break;
                case 1:
                    convertView = inflater.inflate(R.layout.lv_item2, parent, false);
                    vh2 = new ViewHolder(convertView);
                    convertView.setTag(vh2);
                    break;
                case 2:
                    convertView = inflater.inflate(R.layout.lv_item, parent, false);
                    vh1 = new ViewHolder(convertView);
                    convertView.setTag(vh1);
                    break;
            }
        } else {
            switch (type) {
                case 0:
                    vh3 = (ViewHolder) convertView.getTag();
                    break;
                case 1:
                    vh2 = (ViewHolder) convertView.getTag();
                    break;
                case 2:
                    vh1 = (ViewHolder) convertView.getTag();
                    break;
            }
        }
        //赋值
        NewsSummary summary = getItem(position);

        switch (type) {
            case 0:
                setUIData1(vh3, summary);
                break;
            case 1:
                setUIData2(vh2, summary);
                break;
            case 2:
                setUIData3(vh1, summary);
                break;
        }
        //PopuWindow监听
        switch (type) {
            case 0:
                setPop(vh3.image_button, position);
                break;
            case 1:
                setPop(vh2.image_button, position);
                break;
            case 2:
                setPop(vh1.image_button, position);
                break;

        }
        return convertView;
    }

    public void setPop(final View anchorView, final int position) {
        anchorView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mCurPopupWindow = showTipPopupWindow(position, anchorView, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(context, "position" + position, Toast.LENGTH_SHORT).show();
                        list.remove(position);
                        MyBase.this.notifyDataSetChanged();

                    }
                });
            }
        });
    }

    public void setUIData3(ViewHolder holder, NewsSummary summary) {
        holder.tv_ptime.setText(summary.ptime);
        holder.tv_replyCount.setText(summary.replyCount + "评论");
        holder.tv_title.setText(summary.title);
        holder.tv_digest.setText(summary.digest);
        holder.tv_source.setText(summary.source);
    }

    public void setUIData1(ViewHolder holder, NewsSummary summary) {
        setUIData3(holder, summary);
        ImageLoader.getInstance().displayImage(summary.imgsrc, holder.image1, Main2Activity.options);
    }

    public void setUIData2(ViewHolder holder, NewsSummary summary) {
        setUIData3(holder, summary);
        ImageLoader.getInstance().displayImage(summary.imgsrc, holder.image1, Main2Activity.options);
        ImageLoader.getInstance().displayImage(summary.imgextra.get(0).imgsrc, holder.image2, Main2Activity.options);
        ImageLoader.getInstance().displayImage(summary.imgextra.get(1).imgsrc, holder.image3, Main2Activity.options);

    }

    @Override
    public int getViewTypeCount() {
        return 3;
    }

    @Override
    public int getItemViewType(int position) {

        if (list.get(position).imgextra == null) {
            if (list.get(position).imgsrc == null) {
                return TYPE_ITEM3;
            } else {
                return TYPE_ITEM1;//一张图片(0)
            }
        } else {
            return TYPE_ITEM2;//三张图片(1)
        }
    }

    public PopupWindow showTipPopupWindow(int position, final View anchorView, final View.OnClickListener onClickListener) {

        final View contentView = inflater.inflate(R.layout.popu_item, null);

        contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);

        final PopupWindow popupWindow = new PopupWindow(contentView,
                contentView.getMeasuredWidth(), contentView.getMeasuredHeight(), false);

        contentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                onClickListener.onClick(v);
            }
        });

        //调整箭头位置
        contentView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                // 自动调整箭头的位置
                autoAdjustArrowPos(popupWindow, contentView, anchorView);
                contentView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
        });

        // 如果不设置PopupWindow的背景，有些版本就会出现一个问题：无论是点击外部区域还是Back键都无法dismiss弹框
        popupWindow.setBackgroundDrawable(new ColorDrawable());


        popupWindow.setOutsideTouchable(true);

        popupWindow.setTouchable(true);

        popupWindow.setFocusable(false);
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;   // 这里面拦截不到返回键
            }
        });

        // 如果希望showAsDropDown方法能够在下面空间不足时自动在anchorView的上面弹出
        // 必须在创建PopupWindow的时候指定高度，不能用wrap_content
        popupWindow.showAsDropDown(anchorView);

        return popupWindow;
    }

    private void autoAdjustArrowPos(PopupWindow popupWindow, View contentView, View anchorView) {

        View upArrow = contentView.findViewById(R.id.up_arrow);
        View downArrow = contentView.findViewById(R.id.down_arrow);

        //初始化位置数组
        int pos[] = new int[2];//0：x,1:y
        contentView.getLocationOnScreen(pos);//数组初始化，获得位置信息
        Log.d("contentView", "(" + pos[0] + "," + pos[1] + ")");
        int popLeftPos = pos[0];
        Log.d("popLeftPos", "(" + popLeftPos + ")");

        anchorView.getLocationOnScreen(pos);

        int anchorLeftPos = pos[0];
        Log.d("anchorLeftPos", "(" + anchorLeftPos + ")");
        Log.d("anchorView", "(" + pos[0] + "," + pos[1] + ")");
        Log.d("anchorView", "(" + anchorView.getWidth() + "," + upArrow.getWidth() + ")");

        //箭头的X标
        int arrowLeftMargin = anchorLeftPos - popLeftPos + anchorView.getWidth() / 2 - upArrow.getWidth() / 2;

        Log.d("arrowLeftMargin", "(" + arrowLeftMargin + ")");

        upArrow.setVisibility(popupWindow.isAboveAnchor() ? View.INVISIBLE : View.VISIBLE);
        downArrow.setVisibility(popupWindow.isAboveAnchor() ? View.VISIBLE : View.INVISIBLE);

        RelativeLayout.LayoutParams upArrowParams = (RelativeLayout.LayoutParams) upArrow.getLayoutParams();
        upArrowParams.leftMargin = arrowLeftMargin;
        RelativeLayout.LayoutParams downArrowParams = (RelativeLayout.LayoutParams) downArrow.getLayoutParams();
        downArrowParams.leftMargin = arrowLeftMargin;
    }


    //持有类
    class ViewHolder {
        ImageView image1, image2, image3, image_button;
        TextView tv_title;
        TextView tv_source;
        TextView tv_replyCount;
        TextView tv_ptime;
        TextView tv_digest;

        public ViewHolder() {

        }

        public ViewHolder(View convertView) {

            tv_digest = (TextView) convertView.findViewById(R.id.tv_digest);
            tv_ptime = (TextView) convertView.findViewById(R.id.tv_ptime);
            tv_title = (TextView) convertView.findViewById(R.id.tv_title);
            tv_source = (TextView) convertView.findViewById(R.id.tv_source);
            tv_replyCount = (TextView) convertView.findViewById(R.id.tv_replyCount);
            image1 = (ImageView) convertView.findViewById(R.id.image1);
            image2 = (ImageView) convertView.findViewById(R.id.image2);
            image3 = (ImageView) convertView.findViewById(R.id.image3);
            image_button = (ImageView) convertView.findViewById(R.id.image_button);
        }
    }
}
